import React, { Component ,Fragment} from 'react';
import {Layout,Form,Icon,Input,Button,Checkbox,Select,Row,Col,message,Cascader,AutoComplete} from 'antd';
import styled from 'styled-components';
import {connect} from 'dva';
import {addressOptions,formItemLayout,formTailItemLayout} from './constants';
const {Footer,Content} = Layout;
const {Option} = Select;
const CaptchaUrl = `http://127.0.0.1:7001/captcha`
class Login extends Component {
  handleSubmit = (event)=>{
    event.preventDefault();
      //获得表单里里所有的输入值 
    //this.loginForm.props.form.getFieldsValues();直接 取得表单的值
    this.loginForm.props.form.validateFields((err,values)=>{//{username:'',password:''}
       if(err){
           message.error('表单输入失败!');
       }else{
           this.props.dispatch({
               type:this.props.isLogin?'login/login':'login/signup',
               payload:values
           });
       }
    });//验证表表输入是否合法，如果合法获取表单的值 
  }
  changeLoginStatus = ()=>{
    this.props.dispatch({
      type:'login/save',
      payload:{isLogin:!this.props.isLogin}
    });
  }
  render() {
    const {isLogin} = this.props;
    return (
      <Layout>
        <Content>
          <LoginForm
           isLogin={isLogin}
           handleSubmit={this.handleSubmit}
           changeLoginStatus={this.changeLoginStatus}
           wrappedComponentRef={instance =>this.loginForm=instance}
          >
          </LoginForm>
        </Content>
        <Footer style={{textAlign:'center'}}>
            珠峰架构 @2019
        </Footer>
      </Layout>
    )
  }
}
export default connect(
    state=>state.login
)(Login);
//这是我们的登陆和注册表单
class LoginForm extends Component{
    state= {websiteOptions:[],confirmDirty:false}
    handleWebsiteChange = (value)=>{
      if(value){
        this.setState({
          websiteOptions:[".com",'.cn','.org'].map(domain=>`${value}${domain}`)
        });
      }else{
        this.setState({
          websiteOptions:[]
        });
      }
    }
    //每当输入或修改过确认密码之后都要判断一下
    handleConfirmBlur = (event)=>{
      let value = event.target.value;
      this.setState({
        confirmDirty:this.state.confirmDirty||!!value
      });
    }
    compareToFirstPassord = (rule,value,callback)=>{
      if(value && value !== this.props.form.getFieldValue('password')){
        callback('密码和确认密码不匹配');
      }else{
        callback();
      }
    }
    validateConfirmPassword = (rule,value,callback)=>{
      if(value && this.state.confirmDirty){
        this.props.form.validateFields(['confirm'],{force:true});
      }
      callback();
    }
    changCaptcha = (event)=>{
      event.target.src = CaptchaUrl+'?ts='+Date.now();
    }
    render(){
        const {form:{getFieldDecorator},handleSubmit,isLogin,changeLoginStatus} = this.props;
        let country = getFieldDecorator('prefix',{})(
          <Select style={{width:70}}>
          <Option value="+86">+86</Option>
          <Option value="+87">+87</Option>
         </Select>
        );
        return(
           <WrappedForm>
             <Form onSubmit={handleSubmit} style={{width:isLogin?'400px':'500px'}}>
                <h3>欢迎{isLogin?'登录':'注册'}</h3>
                <Form.Item label="用户名" {...formItemLayout}>
                 {
                    getFieldDecorator('username',{
                        initialValue:'',
                        rules:[{required:true,message:'用户名必须输入'}]
                    })(<Input prefix={<Icon type="user"/>} placeholder="请输入用户名"/>)
                 }  
                </Form.Item>
                <Form.Item label="密码" {...formItemLayout}>
                 {
                    getFieldDecorator('password',{
                        rules:[{required:true,message:'密码必须输入'},
                        {validator:this.validateConfirmPassword}
                      ]
                    })(<Input prefix={<Icon type="lock"/>} placeholder="请输入密码"/>)
                 }  
                </Form.Item>
                {
                  !isLogin&&(
                    <Fragment>
                      <Form.Item label="确认密码" {...formItemLayout}>
                      {
                          getFieldDecorator('confirm',{
                              rules:[
                                {required:true,message:'确认密码必须输入'},
                                {validator:this.compareToFirstPassord}
                              ]
                          })(<Input onBlur={this.handleConfirmBlur} prefix={<Icon type="lock"/>} placeholder="请输入确认密码"/>)
                      }  
                    </Form.Item>
                    <Form.Item label="邮箱" {...formItemLayout}>
                    {
                       getFieldDecorator('email',{
                           rules:[{required:true,message:'邮箱必须输入'},{type:'email',message:'必须输入正确的邮箱格式'}]
                       })(<Input prefix={<Icon type="mail"/>} placeholder="请输入确认密码"/>)
                    }  
                   </Form.Item>
                   <Form.Item label="地址" {...formItemLayout}>
                    {
                       getFieldDecorator('address',{
                           rules:[{required:true,message:'地址必须输入'}]
                       })(<Cascader options={addressOptions}/>)
                    }  
                   </Form.Item>
                   <Form.Item label="手机号" {...formItemLayout}>
                    {
                       getFieldDecorator('phone',{
                           rules:[{required:true,message:'手机号必须输入'}]
                       })(<Input addonBefore={country} placeholder="请输入手机号"/>)
                    }  
                   </Form.Item>
                   <Form.Item label="个人主页" {...formItemLayout}>
                    {
                       getFieldDecorator('website',{
                           rules:[{required:true,message:'个人主页必须输入'}]
                       })(<AutoComplete
                          dataSource={this.state.websiteOptions}
                          onSearch={this.handleWebsiteChange}
                       >
                         <Input/>
                       </AutoComplete>)
                    }  
                   </Form.Item>
                   <Form.Item label="验证码" {...formItemLayout} extra="请证明你不是机器人">
                     <Row gutter={8}>
                      <Col span={12}>
                      {
                       getFieldDecorator('captcha',{
                           rules:[{required:true,message:'验证码必须输入'}]
                       })(<Input/>)
                    }  
                      </Col>
                      <Col span={12}> 
                        <img src={CaptchaUrl} onClick={this.changCaptcha}/>
                      </Col>
                     </Row>
                    
                   </Form.Item>
                   <Form.Item {...formTailItemLayout}>
                   {
                       getFieldDecorator('aggrement',{
                         valuePropName:'checked'
                       })(
                         <Checkbox>我已经阅读并同意 <a href="#">协议</a></Checkbox>
                      )
                    }  
                   </Form.Item>
                    </Fragment>
                  )
                }
                
                <Form.Item >
                    <Button style={{width:'100%'}} type="primary" htmlType="submit" >{isLogin?'登录':'注册'}</Button>
                    {isLogin?'没有':'已有'}账号?<a href="#" onClick={changeLoginStatus}>立即{isLogin?'注册':'登录'}</a>
                </Form.Item>
            </Form>
           </WrappedForm>
        )
    }
}
LoginForm = Form.create()(LoginForm);

const WrappedForm = styled.div`
 display:flex;
 justify-content:center;
 align-items:center;
 height:calc(100vh - 70px);
 h3{
     text-align:center;
 }
 form{
     border:1px solid #CCC;
     border-radius:5px;
     padding:20px;
 }
`